package com.askyjt.videosearch.api;

import com.askyjt.videosearch.common.constant.Constant;
import com.askyjt.videosearch.entity.Picture;
import com.askyjt.videosearch.service.PictureService;
import com.askyjt.videosearch.util.MinioUtil;
import com.askyjt.videosearch.util.Result;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.InputStream;
import java.util.List;
import java.util.UUID;

/**
 *
 * @author yangjintao
 */
@RestController
@RequestMapping("/api/picture")
public class PictureApi {

    @Resource
    private PictureService pictureService;

    @Resource
    private MinioUtil minioUtil;

    /**
     * 通过上传的图片查询相似的图片,使用minio服务器
     * @param file topk
     * @return
     */
    @PostMapping("/searchPicture/v1")
    public Result<List<Picture>> searchPicture(@RequestParam("file") MultipartFile file, @RequestParam(defaultValue = "10",value = "topk") Integer topK) {
        if (file.isEmpty() || file.getSize() == 0) {
            return Result.error("error", "文件不能为空！");
        }
        try {
            String fileName;
            if ((fileName = file.getOriginalFilename()) != null) {
                String newName = Constant.MINIO_TMP_PATH + UUID.randomUUID().toString().replaceAll("-", "")
                        + fileName.substring(fileName.lastIndexOf("."));
                InputStream inputStream = file.getInputStream();
                minioUtil.putObject(Constant.MINIO_BUCKET_PICTURE, newName, inputStream, file.getContentType());
                inputStream.close();
                String url = minioUtil.getObjectUrl(Constant.MINIO_BUCKET_PICTURE, newName);
                List<Picture> pictures = pictureService.searchPicture(url, topK);
                return Result.success(pictures);
            }
            return Result.error("error", "文件名不能为空！");
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("error", "上传失败");
        }
    }
}
